/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.cognition.util.j2me;

import javax.microedition.midlet.MIDlet;

/**
 * Utility class that returns system defined properties only.
 * @author richard
 */
public class ApplicationProperties {
    private static Logger logger = SystemLogger.getLogger(SystemLogger.LOGGER_CONSOLE);
    public static final String LOG_TAG = "ApplicationProperties";

    public static MIDlet midlet;

    /**
     * When PLATFORM is set to this value, the platform conforms to the generic
     * J2ME specification only."
     */
    public static final String PLATFORM_STANDARD="Spec J2ME";

    /**
     * When PLATFORM is set to this value, the platform conforms to a RIM
     * phone (e.g. Blackberry).
     */
    public static final String PLATFORM_RIM="RIM";

    /**
     * Identifies the current platform at build time.
     */
    public static final String PLATFORM=PLATFORM_STANDARD;

    /**
     * If true then ServerWorkerRegistry will open a thread for each
     * new transport object that gets picked up from the server socket.
     */
    public static final boolean SERVERWORKER_REGISTRY_MULTITHREAD = false;

    /**
     * Returns a property if it exists from the following sources in the
     * following order:
     * <ol>
     * <li>From a call to System.getProperty
     * <li>From a call to MIDlet.getAppProperty(String).
     * </ol>
     * @param key the key to return the property for
     * @return null if the property doesn't exist.
     */
    public String getProperty(String key){

        String result = getSystemProperty(key);

        if (result != null)
            return result;

        if (midlet == null)
            logger.warn(LOG_TAG, "key " + key +
                    " may originate from midlet but member '" +
                    "ApplicationProperties.midlet' not set.");

        if (midlet != null)
            result = midlet.getAppProperty(key);

        // TODO: Check to see if the property is stored in the RMS in the standard RMS storage for properties named "AppConfiguredProperties".

        return result;
    }

    private static String getSystemProperty(final String name) {
        try {
            return System.getProperty(name);
        } catch (SecurityException ex) {
            return null;
        }
    }

}
